package com.dabai.videobrowser;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.customview.widget.ViewDragHelper;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.dabai.dbutils.data.ListUtils;
import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.uitools.utils.ViewUtils;
import com.dabai.videobrowser.adapter.PreviewAdapter;
import com.dabai.videobrowser.adapter.VideoListAdapter;
import com.dabai.videobrowser.bean.PreviewModel;
import com.dabai.videobrowser.bean.VideoListModel;
import com.dabai.videobrowser.databinding.ActivityMainBinding;
import com.dabai.videobrowser.other.MainUtils;
import com.dabai.videobrowser.ui.BatchRenameActivity;
import com.dabai.videobrowser.utils.MediaFileUtils;
import com.dabai.videobrowser.view.VideoController2;
import com.dueeeke.videoplayer.player.VideoView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Consumer;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding amb;
    Context context;

    ArrayList<String> videoPathList = new ArrayList<>();
    //计次器
    int count = 0;
    private LinearLayoutManager linearLayoutManager;
    private VideoListAdapter videoListAdapter;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        amb = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(amb.getRoot());

        context = this;

        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DBToast.showText(context, "需要储存权限!", false);
                        finish();
                    }
                });

        SharedPreferencesBasicUse.init(context);
        TipAlertDialog.init(context);


        //数据库创建与初始化
        db = openOrCreateDatabase("HistoricalRecord", Context.MODE_PRIVATE, null);
        String create = "create table if not exists GenerateHistoricalRecord(id integer primary key autoincrement,content text not null unique);";
        db.execSQL(create);


        amb.til1.getEditText().setText(SharedPreferencesBasicUse.getString("lastPath", ""));

        amb.button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                MainUtils.showGenerateHistory(context,amb.til1);
                return true;
            }
        });
        //扫描按钮
        amb.button.setOnClickListener(v -> {

            videoPathList = new ArrayList<>();
            count = 0;

            File dir = new File(getEditContent());

            if (!dir.exists()) {
                DBToast.showYellowToast(context, "路径目标不存在!");
                return;
            }
            if (!dir.isDirectory()) {
                DBToast.showYellowToast(context, "路径目标必须是文件夹!");
                return;
            }

            SharedPreferencesBasicUse.setString("lastPath", dir.getAbsolutePath());


            ContentValues in = new ContentValues();
            in.put("content", dir.getAbsolutePath());
            db.insert("GenerateHistoricalRecord", null, in);

            for (File file : Objects.requireNonNull(dir.listFiles())) {

                String fileNameToLowerCase = file.getName().toLowerCase();
                if (fileNameToLowerCase.endsWith(".mp4") ||
                        fileNameToLowerCase.endsWith(".mov") ||
                        fileNameToLowerCase.endsWith(".rmvb") ||
                        fileNameToLowerCase.endsWith(".avi") ||
                        fileNameToLowerCase.endsWith(".flv")) {
                    videoPathList.add(file.getAbsolutePath());
                }
            }

            if (videoPathList.size() <= 0) {
                return;
            }

            initVideoListView(videoPathList);

            playVideo(getVideoListCountPath());

            amb.til1.setVisibility(View.GONE);
            amb.button.setVisibility(View.GONE);
            amb.textView5.setVisibility(View.VISIBLE);

            AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 2, 0);

        });

        amb.videoPlayer.setOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }
            @Override
            public void onPlayStateChanged(int playState) {
                if (playState==VideoView.STATE_PLAYBACK_COMPLETED){
                    down();
                    Log.d("DBTAG", "onPlayStateChanged: ");
                }
            }
        });

        /**
         * 切换视频
         */
        amb.button4.setOnClickListener(v -> {
            up();
        });
        amb.button5.setOnClickListener(v -> {
            down();
        });

        amb.button8.setOnClickListener(v -> {

            File soc = new File(getVideoListCountPath());
            File tag = new File(getRecycleBinDir(), "del_" + soc.getName());

            DBToast.showMethodsFeedbackText(context, soc.renameTo(tag), "归档成功", "归档失败");

            if (videoPathList.size() <= 0) {
                return;
            }
            videoPathList.remove(count);
            videoListAdapter.removeAt(count);

            playVideo(getVideoListCountPath());

        });

        amb.button10.setOnClickListener(v -> {
            amb.drawerLayout.openDrawer(GravityCompat.END);
        });
        amb.button9.setOnClickListener(v -> {
            amb.drawerLayout.openDrawer(GravityCompat.START);
        });

        initProgressSmallButton();

    }

    @Override
    protected void onDestroy() {
        TipAlertDialog.destroyTipLayout();
        super.onDestroy();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initVideoListView(ArrayList<String> videoPathList) {

        linearLayoutManager = new LinearLayoutManager(context);
        amb.recyclerView.setLayoutManager(linearLayoutManager);
        amb.recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));

        ArrayList<VideoListModel> videoListModels = new ArrayList<>();

        TipAlertDialog.getInstance(context).showTipLayout("正在执行...");

        new Thread(() -> {

            for (int i = 0 ; i < videoPathList.size() ;i++) {

                try {
                    File file = new File(videoPathList.get(i));
                    videoListModels.add(new VideoListModel(i+1,file.getName()
                            , MediaFileUtils.millisecondToTimeString(MediaFileUtils.getMediaFileTime(videoPathList.get(i)))
                            , FileUtils.getFileSizeToString(file)));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


            runOnUiThread(() -> {

                TipAlertDialog.getInstance(context).hideTipLayout();

                videoListAdapter = new VideoListAdapter(videoListModels);
                amb.recyclerView.setAdapter(videoListAdapter);

                videoListAdapter.setOnItemClickListener((adapter, view, position) -> {
                    count = position;
                    playVideo(getVideoListCountPath());
                    amb.drawerLayout.closeDrawers();
                });

                videoListAdapter.setOnItemLongClickListener((adapter, view, position) -> {

                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    try {
                        //根据url获取缩略图
                        retriever.setDataSource(videoPathList.get(position));
                        amb.imageView1.setImageBitmap(retriever.getFrameAtTime());

                        VideoListModel videoListModel = (VideoListModel) adapter.getData().get(position);
                        amb.textView3.setText(videoListModel.getId()+". "+videoListModel.getName());

                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } finally {
                        retriever.release();
                    }

                    return true;
                });

            });
        }).start();


    }

    private void initProgressSmallButton() {

        amb.button21.setOnClickListener(v -> percentageJumpProgress(1, 10));
        amb.button22.setOnClickListener(v -> percentageJumpProgress(2, 10));
        amb.button23.setOnClickListener(v -> percentageJumpProgress(3, 10));
        amb.button24.setOnClickListener(v -> percentageJumpProgress(4, 10));
        amb.button25.setOnClickListener(v -> percentageJumpProgress(5, 10));
        amb.button26.setOnClickListener(v -> percentageJumpProgress(6, 10));
        amb.button27.setOnClickListener(v -> percentageJumpProgress(7, 10));
        amb.button28.setOnClickListener(v -> percentageJumpProgress(8, 10));
        amb.button29.setOnClickListener(v -> percentageJumpProgress(9, 10));
        amb.button210.setOnClickListener(v -> percentageJumpProgress(14, 15));

    amb.button31.setOnClickListener(v -> {
        if (!amb.videoPlayer.isPlaying()) {
            return;
        }
        amb.videoPlayer.seekTo(amb.videoPlayer.getCurrentPosition()-5000<0?amb.videoPlayer.getCurrentPosition():amb.videoPlayer.getCurrentPosition()-5000);

    });

    amb.button32.setOnClickListener(v -> {
        amb.videoPlayer.seekTo(amb.videoPlayer.getCurrentPosition()+5000>amb.videoPlayer.getDuration()?amb.videoPlayer.getCurrentPosition():amb.videoPlayer.getCurrentPosition()+5000);

    });


    }

    private void percentageJumpProgress(int a, int b) {
        if (!amb.videoPlayer.isPlaying()) {
            return;
        }
        amb.videoPlayer.seekTo(amb.videoPlayer.getDuration() / b * a);

    }

    private String getVideoListCountPath() {
        if (videoPathList.size() <= 0) {
            DBToast.showYellowToast(context, "视频列表为空!");
            return "";
        }
        try {

            return videoPathList.get(count);
        } catch (Exception e) {
            // DBToast.showYellowToast(context,"视频列表异常,可能是索引出界!");
            count--;
            return videoPathList.get(count);
        }
    }

    private void playVideo(String path) {

        amb.videoPlayer.release();
        amb.videoPlayer.setUrl(path); //设置视频地址
        VideoController2 controller = new VideoController2(this);

        controller.setOnRef(() -> {

            File soc = new File(getVideoListCountPath());
            File tag = new File(getRecycleBinDir(), "del_" + soc.getName());

            DBToast.showMethodsFeedbackText(context, soc.renameTo(tag), "归档成功", "归档失败");

            if (videoPathList.size() <= 0) {
                return;
            }
            videoPathList.remove(count);
            videoListAdapter.removeAt(count);

            playVideo(getVideoListCountPath());

        });
        controller.setOnVoice(this::down);
        controller.setOnWrite(this::up);

        controller.setEnableInNormal(true);
        controller.addDefaultControlComponent(new File(path).getName(), false);
        amb.videoPlayer.setVideoController(controller);
        amb.videoPlayer.start(); //开始播放，不调用则不自动播放

        setTitle(count + 1 + "/" + videoPathList.size());

        amb.textView5.setText((count + 1) +". "+ new File(getVideoListCountPath()).getName());

        linearLayoutManager.scrollToPosition(count);

        accordingToPreview(path,MediaFileUtils.getMediaFileTime(path));

    }

    private void accordingToPreview(String path,long duration) {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        amb.recyclerView2.setLayoutManager(linearLayoutManager);
        amb.recyclerView2.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));


        ArrayList<PreviewModel> arrayList = new ArrayList<>();

        new Thread(() -> {

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                //根据url获取缩略图
                retriever.setDataSource(path);

                for (int i=1;i<=9;i++){
                    //获得第一帧图片
                    long time = duration/10*i;

                    Bitmap bitmap = retriever.getFrameAtTime(time*1000);

                    arrayList.add(new PreviewModel(
                            MediaFileUtils.millisecondToTimeString(time)
                            , bitmap));
                }


            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } finally {
                retriever.release();
            }

            runOnUiThread(() -> {
                PreviewAdapter previewAdapter = new PreviewAdapter(arrayList);
                amb.recyclerView2.setAdapter(previewAdapter);

                previewAdapter.setOnItemClickListener((adapter, view, position) -> {


                    long time = duration/10*(position+1);
                    amb.videoPlayer.seekTo(time);

                    amb.drawerLayout.closeDrawers();
                });

            });
        }).start();


    }


    public void up() {
        if (count > 0) {
            count--;
        } else {
            DBToast.showText(context, "已经是第一个了!", false);
            return;
        }

        playVideo(getVideoListCountPath());


    }

    public void down() {
        if (count < videoPathList.size() - 1) {
            count++;
        } else {
            DBToast.showText(context, "已经是最后一个了!", false);
            return;
        }

        playVideo(getVideoListCountPath());

    }


    /**
     * 获取编辑框内容
     *
     * @return {@link String}
     */
    public String getEditContent() {
        return Objects.requireNonNull(amb.til1.getEditText()).getText().toString();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.delAll) {
            new MaterialAlertDialogBuilder(context).setTitle("警告").setMessage("包含" + getRecycleBinDir().listFiles().length + "个文件,是否清空?")
                    .setPositiveButton("确定", (dialog, which) -> {
                        boolean isOk = FileUtils.delete(getRecycleBinDir());
                        DBToast.showText(context, isOk ? "成功" : "失败", isOk);
                    }).setNeutralButton("取消", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
            return true;
        }
        if (itemId == R.id.rename) {
            ActivityUtils.startActivity(this, BatchRenameActivity.class);
            return true;
        }
        if (itemId == R.id.scan) {

            amb.til1.setVisibility(View.VISIBLE);
            amb.button.setVisibility(View.VISIBLE);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }


    /**
     * 得到回收站dir
     *
     * @return {@link File}
     */
    public File getRecycleBinDir() {
        File file = getExternalFilesDir("RecycleBin");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }


    @Override
    public void onConfigurationChanged(@NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (amb.videoPlayer.isFullScreen()) {
                amb.videoPlayer.onBackPressed();
                return true;
            }

            if (amb.drawerLayout.isDrawerOpen(GravityCompat.END)||amb.drawerLayout.isDrawerOpen(GravityCompat.START)){
                amb.drawerLayout.closeDrawers();
                return true;
            }

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                DabaiUtils.backHome(context);
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

}